package com.studyv3.test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.studyv3.common.core.domain.PageBean;
import com.studyv3.common.core.domain.R;
import com.studyv3.test.domain.Products;
import com.studyv3.test.mapper.ProductsMapper;
import com.studyv3.test.service.ProductsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
* @author 侯杰
* @description 针对表【products(采购列表)】的数据库操作Service实现
* @createDate 2024-05-06 10:49:15
*/
@Service
@RequiredArgsConstructor
public class ProductsServiceImpl implements ProductsService{
    private final ProductsMapper productsMapper;

    @Override
    public R add(Products add) {
        add.setCreateTime(LocalDateTime.now());
        add.setUpdateTime(LocalDateTime.now());
        if(productsMapper.selectOne(new LambdaQueryWrapper<Products>().eq(Products::getName,add.getName())) != null){
            return R.fail("商品已存在");
        }
        if (productsMapper.insert(add) > 0){
            return R.ok("添加成功");
        }
        return R.fail("添加失败");
    }

    @Override
    public R deleteUserByIds(Integer[] ids) {
        productsMapper.deleteBatchIds(Arrays.asList(ids));
        return R.fail("删除成功");
    }

    @Override
    public R queryAll() {
        return R.ok(productsMapper.selectList(new LambdaQueryWrapper<Products>().orderByAsc(Products::getName)));
    }

    @Override
    public PageBean<Products> list(Integer pageNum, Integer pageSize, String a, String b, String c) {
        //条件分页
        //1.创建PageBean对象
        PageBean<Products> pb = new PageBean<>();
        //2.开启分页查询(会自动拼接sql)
        PageHelper.startPage(pageNum,pageSize);
        //3.调用mapper
        LambdaQueryWrapper<Products> wrapper = new LambdaQueryWrapper<>();
        if(!Objects.isNull(a)){
            wrapper.like(Products::getName,a);
        }
        if(!Objects.isNull(b)){
            wrapper.ge(Products::getPrice,b);
        }
        if(!Objects.isNull(c)){
            wrapper.le(Products::getPrice,c);
        }
        List<Products> as = productsMapper.selectList(wrapper);
//        System.out.println(as);
        //4.结果转为PageHelper的page对象
        Page<Products> p = (Page<Products>) as;
        //Page提供了方法，可以获取PageHelper分页查询后得到的总记录条数和当前页数据
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public R update(Products buyProducts) {
        buyProducts.setUpdateTime(LocalDateTime.now());
        if(productsMapper.updateById(buyProducts)>0){
            return R.ok("更新成功");
        }
        return R.fail("更新失败");
    }

    @Override
    public Products productsById(Integer id) {

        return productsMapper.selectById(id);
    }

}



